package com.tulele.vtool.handler;

import com.tulele.vtool.bus.mapper.log.PushDetailLogMapper;
import com.tulele.vtool.bus.mapper.log.PushHeadLogMapper;
import com.tulele.vtool.bus.model.UserInfo;
import com.tulele.vtool.bus.model.log.PushHeadLog;
import com.tulele.vtool.bus.model.thirdparty.WxMpSubscribeMessageInfo;
import com.tulele.vtool.bus.service.IArticleService;
import com.tulele.vtool.bus.service.IUserService;
import com.tulele.vtool.task.async.*;
import com.tulele.vtool.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.*;

@Slf4j
@RestController
public class CallHandler {

    @Autowired
    private NextArticlePushAsyncTask nextArticlePushAsyncTask;

    @Autowired
    private PositiveEnergyArticlePushAsyncTask positiveEnergyArticlePushAsyncTask;

    @Autowired
    private FirstTimeArticlePushAsyncTask firstTimeArticlePushAsyncTask;

    @Autowired
    private IUserService userService;

    @Autowired
    private UploadTempMsgPushAsyncTask uploadTempMsgPushAsyncTask;

    @Autowired
    private PushHeadLogMapper pushHeadLogMapper;

    @Autowired
    private PushDetailLogMapper pushDetailLogMapper;

    //接口项目调用,20200219,24小时提示 后推送一批文章
    @PostMapping(value = "/callFifthTime", produces = "application/json;charset=UTF-8")
    public String callFifthTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {

        log.info("[CallHandler callFifthTime] 触发了  userId=" + userId);
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        nextArticlePushAsyncTask.execute("wxPushUser" + userId,userInfo, profile);
        return "callFifthTime调用完成";
    }

    //换一批视频
    @PostMapping(value = "/callVideo", produces = "application/json;charset=UTF-8")
    public String callVideo(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        nextArticlePushAsyncTask.executeVideo("wxPushUser" + userId,userInfo, profile);
        return "callVideo调用完成";
    }

    //点击菜单10秒推送
    @PostMapping(value = "/call10sec", produces = "application/json;charset=UTF-8")
    public String call10sec(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        nextArticlePushAsyncTask.execute_10sec(userInfo, profile);
        return "callVideo调用完成";
    }

    @PostMapping(value = "/callFirstTime", produces = "application/json;charset=UTF-8")
    public String callFirstTime(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        firstTimeArticlePushAsyncTask.execute2("wxPushUser" + userId,userInfo, profile);
        return "callFirstTime调用完成";
    }

    //接口项目调用,20200521 推送正能量文章 随机5篇
    @PostMapping(value = "/pushPositiveEnergy", produces = "application/json;charset=UTF-8")
    public String pushPositiveEnergy(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        positiveEnergyArticlePushAsyncTask.execute("wxPushUser" + userId,userInfo, profile);
        return "pushPositiveEnergy调用完成";
    }

    //接口项目调用,20200521 推送财税文章 随机5篇
    @PostMapping(value = "/pushUserArticleType", produces = "application/json;charset=UTF-8")
    public String pushCaiShui(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile, @RequestHeader("articleTypeId") String articleTypeId) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        positiveEnergyArticlePushAsyncTask.executeUserArticleType("wxPushUser" + userId,userInfo, profile, Integer.valueOf(articleTypeId));
        return "pushPositiveEnergy调用完成";
    }

    //接口项目调用,20210607 推送指定的品牌文章
    @PostMapping(value = "/pushBrandArticle", produces = "application/json;charset=UTF-8")
    public String pushBrandArticle(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile, @RequestHeader("brandId") String brandId) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        positiveEnergyArticlePushAsyncTask.execute_brand("wxPushUser" + userId,userInfo, profile, brandId);
        return "pushBrandArticle调用完成";
    }

    //接口项目调用,20201111 开单学堂 文章
    @PostMapping(value = "/push_KDXT", produces = "application/json;charset=UTF-8")
    public String push_KDXT(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) throws Exception {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        positiveEnergyArticlePushAsyncTask.execute_KDXT("wxPushUser" + userId,userInfo, profile);
        return "push_KDXT调用完成";
    }

    //接口项目调用,20210615 发送“上传成功通知”
    @PostMapping(value = "/uploadMsgPush", produces = "application/json;charset=UTF-8")
    public String UploadMsgPush(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile) {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        uploadTempMsgPushAsyncTask.execute(userInfo, profile, 0);
        return "uploadMsgPush调用完成";
    }

    //后台项目调用,20210615 发送“上传成功通知” (测试)
    @CrossOrigin
    @PostMapping(value = "/UploadMsgPushBrandIdTest", produces = "application/json;charset=UTF-8")
    public String UploadMsgPushBrandIdTest(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile, @RequestHeader("brandId") Integer brandId, @RequestHeader("articleId") Integer articleId) {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        uploadTempMsgPushAsyncTask.executeBrandId(userInfo, profile, 0, brandId, articleId);
        return "UploadMsgPushBrandIdTest调用完成";
    }

    //接口项目调用，20211207,发送图文的文章
    @PostMapping(value = "/pushArticleByEnId", produces = "application/json;charset=UTF-8")
    public String pushArticleByEnId(@RequestHeader("userId") String userId, @RequestHeader("profile") String profile,  @RequestHeader("enArticleId") String enArticleId) {
        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        uploadTempMsgPushAsyncTask.pushArticleByEnId(userInfo, profile, enArticleId);
        return "pushArticleEnId调用完成";
    }

    //后台项目调用,20210615 发送“上传成功通知”
    @CrossOrigin
    @PostMapping(value = "/UploadMsgPushBrandId", produces = "application/json;charset=UTF-8")
    public String UploadMsgPushBrandId(@RequestHeader("profile") String profile, @RequestHeader("brandId") Integer brandId, @RequestHeader("articleId") Integer articleId) throws InterruptedException {

        PushHeadLog pushHeadLog = new PushHeadLog();
        pushHeadLog.setPushName("品牌文章上架推送");
        pushHeadLog.setMsgType(14);
        pushHeadLog.setMsgTypeName("品牌文章上架推送");
        pushHeadLog.setSumCount(0);
        pushHeadLog.setCreateTime(new Date());
        pushHeadLog.setGzhCode(profile);

        pushHeadLogMapper.addPushHeadLog(pushHeadLog);
        Integer headId = pushHeadLog.getId();

        List<UserInfo> userList = userService.getUserByBrandId(profile,brandId);
        for (UserInfo userInfo : userList) {
            uploadTempMsgPushAsyncTask.executeBrandId(userInfo, profile, headId,brandId,articleId);
        }
        return headId.toString();
    }

    @CrossOrigin
    @PostMapping(value = "/updatePushHeadLog", produces = "application/json;charset=UTF-8")
    public String updatePushHeadLog(@RequestHeader("headId") Integer headId) throws InterruptedException {

        PushHeadLog pushHeadLogU = new PushHeadLog();
        pushHeadLogU.setId(headId);
        pushHeadLogU.setSuccessCount(pushDetailLogMapper.getSuccessCount(headId));
        pushHeadLogU.setErrCount(pushDetailLogMapper.getErrCount(headId));
        pushHeadLogU.setUpdateTime(new Date());
        pushHeadLogU.setEndTime(new Date());

        pushHeadLogMapper.updatePushHeadLog(pushHeadLogU);
        return headId.toString();
    }

    /**
     * 微信公众号发送统一订阅消息
     * @param userId 用户ID
     * @param accessToken 微信AccessToken
     * @param wxMpSubscribeMessageInfo 封装实体
     * @return
     */
    @PostMapping(value = "/sendSubscribeMessage", produces = "application/json;charset=UTF-8")
    public Map<String, Object> sendSubscribeMessage(@RequestHeader("userId") String userId,
                                       @RequestHeader("accessToken") String accessToken,
                                       @RequestBody WxMpSubscribeMessageInfo wxMpSubscribeMessageInfo) {
        if (StringUtils.isBlank(userId) || !StringUtils.isNumeric(userId) || StringUtils.isBlank(accessToken) || wxMpSubscribeMessageInfo == null) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", 400);
            resultMap.put("msg", "参数异常");
            resultMap.put("data", null);
            return resultMap;
        }

        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/bizsend?access_token=ACCESS_TOKEN";
        url.replace("ACCESS_TOKEN", accessToken);

        UserInfo userInfo = userService.queryUserInfo(Integer.valueOf(userId));
        wxMpSubscribeMessageInfo.setToUser(userInfo.getOpenId());

        Map<String, Object> params = new HashMap<>();
        params.put("touser", wxMpSubscribeMessageInfo.getToUser());
        params.put("template_id", wxMpSubscribeMessageInfo.getTemplateId());
        // 跳转页面
        if (StringUtils.isNotBlank(wxMpSubscribeMessageInfo.getPage())) {
            params.put("page", wxMpSubscribeMessageInfo.getPage());
        }
        // 跳转小程序页面
        WxMpSubscribeMessageInfo.MiniProgram miniProgram = wxMpSubscribeMessageInfo.getMiniProgram();
        if (miniProgram != null && StringUtils.isNotBlank(miniProgram.getAppid()) && StringUtils.isNotBlank(miniProgram.getPagepath())) {
            params.put("miniprogram", wxMpSubscribeMessageInfo.getMiniProgram());
        }
        params.put("data", wxMpSubscribeMessageInfo.getData());

        String responseText = "";
        try {
            responseText = HttpClientUtil.httpPostRequest(url, params);
        } catch (UnsupportedEncodingException e) {
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("code", 500);
            resultMap.put("msg", "失败");
            resultMap.put("data", e.getMessage());
            return resultMap;
        }
        log.info("[responseText] = {}", responseText);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("code", 200);
        resultMap.put("msg", "成功");
        resultMap.put("data", responseText);
        return resultMap;
    }
}
